const { Sequelize } = require('sequelize');

// 创建 SQLite 数据库连接
const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: '../../wechat.db', // 修改为相对路径指向根目录
  logging: false // 关闭 SQL 日志输出
});

// 定义消息模型
const Message = sequelize.define('Message', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  sender_id: {
    type: Sequelize.INTEGER,
    allowNull: false
  },
  receiver_id: {
    type: Sequelize.INTEGER,
    allowNull: false
  },
  conversation_id: {
    type: Sequelize.STRING,
    allowNull: false
  },
  content: {
    type: Sequelize.TEXT,
    allowNull: false
  },
  message_type: {
    type: Sequelize.STRING,
    defaultValue: 'text'
  },
  created_at: {
    type: Sequelize.DATE,
    defaultValue: Sequelize.NOW
  }
}, {
  tableName: 'messages',
  timestamps: false,
  createdAt: 'created_at'
});

// 定义用户模型（用于关联查询）
// 修改用户模型
const User = sequelize.define('User', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  username: {
    type: Sequelize.STRING,
    allowNull: false
  },
  phone: {
    type: Sequelize.STRING,
    allowNull: false
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false
  },
  // 添加在线状态字段
  is_online: {
    type: Sequelize.BOOLEAN,
    defaultValue: false
  },
  last_online: {
    type: Sequelize.DATE
  }
}, {
  tableName: 'user',
  timestamps: false
});

// 添加更新用户最后在线时间的函数
exports.updateLastOnline = async function(userId) {
  try {
    await User.update(
      { last_online: new Date() },
      { where: { id: userId } }
    );
  } catch (error) {
    console.error('更新用户最后在线时间失败:', error);
  }
};

// 建立关联关系
Message.belongsTo(User, { foreignKey: 'sender_id', as: 'sender' });

// 初始化数据库
async function initDB() {
  try {
    // 同步模型到数据库（如果表不存在则创建）
    await sequelize.sync();
    console.log('SQLite 数据库连接成功');
  } catch (error) {
    console.error('SQLite 数据库连接失败:', error);
  }
}

// 导出数据库连接和模型
exports.sequelize = sequelize;
exports.Message = Message;
exports.User = User;
exports.initDB = initDB;